﻿using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using Microsoft.CodeAnalysis;

namespace AutoCADDotNetLibrary
{
    [Generator]
    public class CodeGenerator : ISourceGenerator
    {
        private (string Name, string CADVersion, string Group, string FileContent)[] _files;

        public void Initialize(GeneratorInitializationContext context)
        {
            Assembly ass = Assembly.GetExecutingAssembly();

            _files = ass.GetManifestResourceNames().Select(x =>
            {
                Match r = Regex.Match(x, @"\.(.+?)(_(.+?))?\.cs$", RegexOptions.RightToLeft);
                Match g = Regex.Match(x, @"\.(.*)\.", RegexOptions.RightToLeft);
                using (StreamReader file = new StreamReader(ass.GetManifestResourceStream(x)))
                {
                    return (Name: r.Groups[1].Value, CADVersion: r.Groups[3].Value, Group: g.Groups[1].Value + ".", FileContent: (file.ReadToEnd()));
                }
            }).ToArray();

            //不变的文件直接写入
            context.RegisterForPostInitialization((i) =>
            {
                _files.Where(x => string.IsNullOrEmpty(x.CADVersion)).ToList().ForEach(x => i.AddSource($"{x.Group}{x.Name}.g.cs", x.FileContent));
            });
        }

        public void Execute(GeneratorExecutionContext context)
        {
            //有条件的文件写入
            INamedTypeSymbol app = context.Compilation.GetTypeByMetadataName("Autodesk.AutoCAD.DatabaseServices.HostApplicationServices");
            if (app != null)
            {
                if (app.ContainingAssembly.Identity.Version >= new Version(19, 0, 0, 0))
                {
                    //AutoCAD2013及以上
                    _files.Where(x => x.CADVersion == "2013+").ToList().ForEach(x => context.AddSource($"{x.Group}{x.Name}_{x.CADVersion}.g.cs", x.FileContent));
                }
                else if (app.ContainingAssembly.Identity.Version < new Version(19, 0, 0, 0))
                {
                    //AutoCAD2012以下
                    _files.Where(x => x.CADVersion == "2012-").ToList().ForEach(x => context.AddSource($"{x.Group}{x.Name}_{x.CADVersion}.g.cs", x.FileContent));
                }
            }
        }
    }
}
